import os
import time
import pymysql
from flask import Blueprint, request
from flask import render_template, send_from_directory, make_response
from flask_restful import Resource, Api

FileManager = Blueprint('FileManager', __name__)
api = Api(FileManager)


class upload(Resource):
    def post(self):
        if request.method == 'POST':
            f = request.files['file']  # 获取前端上传的文件名，通过f.filename获取具体的名称
            # 版本号
            version = request.form["version"]
            # 升级说明
            msg = request.form["msg"]
            # 类型
            _type = request.form["type"]
            # 版本号数字
            version_int = request.form["version_int"]
            # 强制升级
            is_power = request.form["is_power"]
            # 是否最新版
            is_new = request.form["is_new"]
            # 检查文件夹是否存在，如果不存在，则创建
            if not os.path.exists(os.getcwd() + '/' + 'static/upload/'):
                os.mkdir(os.getcwd() + '/' + 'static/upload/')

            # 保存上传的文件到配置的地址中
            f.save(os.path.join('static/upload/', f.filename))
            url = request.host_url + 'download?filename=' + f.filename
            # 保存数据到MySQL数据库
            creatUpdate(_type, version, version_int, is_power, url, msg, is_new)
            return make_response(render_template('upload.html',
                                                 names=os.listdir('static/upload/'),
                                                 as_attachment=True))  # 上传图片成功之后，显示文件夹下所有图片的名称，然后再前端渲染
        else:
            return '提交方式错误'


class download(Resource):
    def get(self):
        filename = request.args.get('filename')
        dirpath = os.path.join(os.getcwd(),
                               'static/upload')  # 这里是下在目录，从工程的根目录写起，比如你要下载static/js里面的js文件，这里就要写static/js
        return send_from_directory(dirpath, filename, as_attachment=True)  # as_attachment=True 一定要写，不然会变成打开，而不是下载


class files(Resource):
    def get(self):
        return make_response(render_template('upload.html',
                                             names=os.listdir('static/upload/'),
                                             as_attachment=True))  # 上传图片成功之后，显示文件夹下所有图片的名称，然后再前端渲染


api.add_resource(upload, '/upload')
api.add_resource(download, '/download')
api.add_resource(files, '/files')


def creatUpdate(_type, version, version_int, is_power, url, msg, is_new):
    server = '47.93.162.110'
    user = 'cloud'
    password = 'zdQmmt!yHH7Oa4N24Yd%#fMRzV%VwT*onL4kJ@qi17jaNIjVtL'
    # 连接数据库
    config = {
        'host': '47.93.162.110',
        'port': 3306,
        'user': 'cloud',
        'password': 'zdQmmt!yHH7Oa4N24Yd%#fMRzV%VwT*onL4kJ@qi17jaNIjVtL',
        'database': 'cloud',
        'charset': 'utf8mb4',
        'cursorclass': pymysql.cursors.Cursor,
    }

    conn = pymysql.connect(**config)  # 获取连接
    cursor = conn.cursor()  # 获取游标
    cursor.execute("update app_update set is_new='0' where is_new='1' and type=" + _type)
    # # 插入数据，注：与sqlserver有些区别
    # cursor.execute("INSERT INTO app_update VALUES('%s','%s','%s','%s','%s','%s','%s')" % (
    #     _type, version, version_int, is_power, url, msg, is_new))
    _id = str(int(time.time()))
    _sql = "insert into app_update(`id`,`type`,`version`,`version_int`,`is_power`,`url`,`msg`,`is_new`) " \
           "values(" + _id + ",'" + _type + "','" + version + "','" + version_int + "','" + is_power \
           + "','" + url + "','" + msg + "','" + is_new + "')"
    cursor.execute(_sql)
    # 提交数据，才会写入表格
    conn.commit()
    # 关闭游标关闭数据库
    cursor.close()
    conn.close()
